package com.dage.salesflow.service;

import com.dage.salesflow.kit.Ret;
import com.dage.salesflow.model.Role;
import com.jfinal.aop.Inject;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import io.jboot.aop.annotation.Bean;
import io.jboot.service.JbootServiceBase;

@Bean
public class RoleService extends JbootServiceBase<Role> {
	@Inject
	UserService userService;

	/**
	 * 角色管理分页
	 *
	 * @param roleName
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	public Page<Role> listByPage(String roleName, int pageNum, int pageSize) {
		Kv cond = Kv.create();
		if (StrKit.notBlank(roleName)) {
			cond.set("roleName", roleName);
		}
		return DAO.template("role.listByPage", cond).paginate(pageNum, pageSize);
	}

	/**
	 * 设置角色菜单和权限
	 *
	 * @return
	 */
	public boolean saveResource(int roleId, int type, Integer[] ids) {
		return Db.tx(() -> {
			Db.delete("DELETE FROM t_role_resource WHERE role_id=? AND resource_id IN(SELECT id FROM t_resource WHERE `type`=?)", roleId, type);
			SqlPara sqlPara = DAO.template("role.saveMenu", Kv.by("roleId", roleId).set("ids", ids)).getSqlPara();
			Db.update(sqlPara);
			return true;
		});
	}

	/**
	 * 设置角色首页
	 *
	 * @param roleId 角色id
	 * @param homeId 菜单id
	 */
	public boolean setHome(int roleId, int homeId) {
		Integer id = Db.queryInt("SELECT p.id FROM `t_resource` p,t_role_resource rp WHERE p.id=rp.resource_id AND role_id=? AND p.type=2", roleId);
		if (id != null && id > 0) {
			Db.update("UPDATE t_role_resource SET resource_id=? WHERE role_id=? AND resource_id=?", homeId, roleId, id);
			return true;
		} else {
			Record record = new Record();
			record.set("role_id", roleId);
			record.set("resource_id", homeId);
			return Db.save("t_role_resource", record);
		}
	}

	/**
	 * 删除角色
	 *
	 * @param id
	 * @return
	 */
	public Ret del(int id) {
		long userNum = userService.getUserNum(id);
		if (userNum > 0) {
			return Ret.err(2);
		} else {
			boolean tx = Db.tx(() -> {
				boolean role = deleteById(id);
				Db.delete("DELETE FROM t_role_resource WHERE role_id=?", id);
				return role;
			});
			if (tx) {
				return Ret.ok();
			} else {
				return Ret.err("删除失败");
			}
		}
	}
}